package com.cypher.encryptionanddecryption.fragment.protocol.nb25;

import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.activity.BluetoothCommunicationActivity;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;
import com.cypher.encryptionanddecryption.fragment.protocol.AbstractProtocolFragment;
import com.cypher.encryptionanddecryption.util.AESUtils;
import com.cypher.encryptionanddecryption.util.HexUtils;
import com.cypher.encryptionanddecryption.util.Nb25ProtocolUtils;
import com.cypher.encryptionanddecryption.watcher.DecimalDigitsWatcher;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * NB2.5协议简单编辑框
 * 只适用于一个编辑框的读写协议
 */
public class SimpleEditFragment  extends AbstractProtocolFragment {
    private BluetoothCommunicationActivity activity;
    private CommunicationBean bean;
    private Map<String, Object> attr;
    private TextView title;
    private EditText content;
    private Handler handler;
    /**
     * 定义输入框最大长度，默认为0
     */
    private int maxLength = 0;
    /**
     * 定义输入框输入类型，默认为否
     */
    private boolean isInteger = false;
    /**
     * 定义小数点后几位，默认为0
     */
    private int decimalDigits = 0;
    /**
     * 命令是否以密文方式返回
     */
    private boolean encrypt = false;
    /**
     * 发送码长度
     */
    private int hexLength = 0;
    public SimpleEditFragment(BluetoothCommunicationActivity activity, CommunicationBean bean) {
        this.activity = activity;
        this.bean = bean;

        attr = bean.getAttr();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_nb25_simple_edit, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        title = view.findViewById(R.id.simple_edit_title);
        title.setText(bean.getName() + "：");
        content = view.findViewById(R.id.simple_edit_data);
        handler = new Handler();
        initFragment();
    }

    /**
     * 初始化简单编辑框通信界面
     */
    private void initFragment() {

        // 如果扩展属性为空，则不做任何限制
        if (attr == null) {
            return;
        }
        if (attr.containsKey("encrypt")) {
            encrypt = attr.get("encrypt") == null ? false : (boolean) attr.get("encrypt");
        }
        // 输入框设置长度
        if (attr.containsKey("maxLength")) {
            maxLength = attr.get("maxLength") == null ? 0 : (Integer) attr.get("maxLength");
            if (maxLength > 0) {
                // 定义输入框过滤器
                InputFilter[] inputFilters = new InputFilter[1];
                // 设置输入框输入内容长度
                inputFilters[0] = new InputFilter.LengthFilter(maxLength);
                content.setFilters(inputFilters);
            }
        }
        // 设置输入框输入类型
        if (attr.containsKey("integer")) {
            isInteger = attr.get("integer") == null ? false : (Boolean)attr.get("integer");
            // 如果是整形，设置输入框只能输入数字
            if (isInteger) {
                if (attr.containsKey("decimalDigits")) {
                    // 获取小数点位数
                    decimalDigits = attr.get("decimalDigits") == null ? 0 : (Integer) attr.get("decimalDigits");
                    // 如果小数点位数不大于0，设置输入框只能输入整数
                    if (decimalDigits <= 0) {
                        content.setInputType(InputType.TYPE_CLASS_NUMBER);
                        return;
                    }
                    // 设置输入框输入整数或小数
                    content.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    // 设置小数点后位数限制
                    content.addTextChangedListener(new DecimalDigitsWatcher(content, decimalDigits));
                }
            }
        }

    }
    @Override
    public void fillFragment(String data) {
        // 清空内容
        content.setText("");

        Runnable r = () -> {
            String formatData = Nb25ProtocolUtils.formatReceiveData(data);
//            // 如果是密文方式返回，需要解密，如当前累计气量
//            if (encrypt)
//                formatData = AESUtils.decrypt(activity.getAesKey(), formatData);
            reader(formatData);
        };
        handler.postDelayed(r, 200);
    }

    @Override
    public String getHexCode(String rwType) {
        if (StringUtils.equals("read", rwType)) {
            return Nb25ProtocolUtils.getReadCommand(bean.getHexCode(), PROTOCOL_VERSION);
        }
        // 组包
        return getData();
    }

    /**
     * 渲染页面
     * @param data
     */
    private void reader(String data) {
        try {
            switch (bean.getHexCode()) {
                case "2003": // 表号参数
                    int len = Integer.parseInt(data.substring(0, 2), 16);
                    content.setText(HexUtils.ascToStr(data.substring(2, len * 2 + 2)));
                    break;
                case "2012": // APN
                    content.setText(HexUtils.ascToStr(data));
                    break;
                case "0003": // 当前累计气量
                    data = AESUtils.decrypt(activity.getAesKey(), data).substring(0, 8);
                    content.setText(HexUtils.formatDouble(
                            HexUtils.integerToDouble(Integer.parseInt(data, 16), decimalDigits), decimalDigits));
                    break;
                default:
                    // 输入框为整形
                    if (isInteger) {
                        content.setText(HexUtils.formatDouble(
                                HexUtils.integerToDouble(Integer.parseInt(data, 16), decimalDigits), decimalDigits));
                    }
            }
        } catch (Exception e) {
            Toast.makeText(activity, bean.getName() + "读取失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取写入数据
     * @return
     */
    private String getData() {
        String txt = content.getText().toString().trim();
        if (StringUtils.isEmpty(txt)) {
            Toast.makeText(activity, bean.getName() + "不能为空", Toast.LENGTH_SHORT).show();
            return "";
        }
        if (attr.containsKey("hexLength")) {
            hexLength = attr.get("hexLength") == null ? 0 : (Integer) attr.get("hexLength");
        }
        // 需要发送的数据域
        String data = "";
        switch (bean.getHexCode()) {
            case "2003": // 表号参数
                String txtLengthHex = HexUtils.paddingLeft(Integer.toHexString(txt.length()), 2);
                data = txtLengthHex + HexUtils.strToAsc(HexUtils.paddingRight(txt, 32));
                break;
            case "2012": // APN
                data = HexUtils.paddingRight(HexUtils.strToAsc(txt), 64);
                break;
            default:
                // 输入框为整形
                if (isInteger) {
                    data = HexUtils.doubleToHex(Double.parseDouble(txt), decimalDigits, hexLength);
                }
        }
        // 如果数据域为空则不去计算发送码
        if (StringUtils.isEmpty(data)) {
            Toast.makeText(activity, bean.getName() + "未获取到数据域", Toast.LENGTH_SHORT).show();
            return data;
        }
        return Nb25ProtocolUtils.getWriteCommand(bean.getHexCode(), data, PROTOCOL_VERSION);
    }
}
